# -*- coding: utf-8 -*-
import logging
import math
import random
from random import choice
from string import digits
from odoo import fields, models, api

_logger = logging.getLogger(__name__)


class TranslationModifyTest(models.Model):
    _name = 'translation.modify.test'
    _description = '翻译修改测试'

    @api.model
    def _lang_get(self):
        return self.env['res.lang'].get_installed()

    name = fields.Char('名称')
    model_id = fields.Many2one('ir.model', required=True, string='模型', ondelete="cascade", domain="[('field_id.translate', '!=', False)]")
    field_id = fields.Many2one('ir.model.fields', string='选择修改可翻译的字段', ondelete="cascade", domain="[('model_id', '=', model_id),('translate', '!=', False)]", help="显示可翻译的字段名称")
    language = fields.Selection(selection=_lang_get, string="选择语言", default=lambda self: self.env.lang)
    after_modification_language = fields.Selection(selection=_lang_get, string="修改之后为语言", default=lambda self: self.env.lang)

    def act_modify(self):
        # 根据选择的模型，使用翻译的字段，筛选出数据，返回的列表只包含翻译的字段内容，结构为列表里每条数据的结构是一个字典模式，翻译字段为键，内容为值
        # docs = self.env[self.model_id.model].search_read(domain, [self.field_id])
        # 根据选择的模型，使用翻译的字段，筛选出数据，返回的列表包含模型数据，模型为指定的语言环境数据内容
        lang_docs = self.env[self.model_id.model].search([]).with_context(lang=self.language)
        after_language = self.env[self.model_id.model].with_context(lang=self.after_modification_language).search_read([], [self.field_id.name])
        # 排序
        now_lang_docs = sorted(lang_docs, key=lambda x: x.id, reverse=False)
        now_after_language = sorted(after_language, key=lambda x: x['id'], reverse=False)

        for mode, v in zip(now_lang_docs, now_after_language):
            mode.write({self.field_id.name: v[self.field_id.name]})

            # _logger.warning(f"显示参数：{mode,v}")
